<template>
  <view class="order-page u-p-20">
    <view class="u-font-lg u-m-b-20" style="margin-left: 120px;">🧾 您选购的菜品</view>
    <up-divider text="分割线" :dot="true" />

    <view v-for="(item, index) in cartList" :key="index" class="u-m-b-20">
      <u-card>
        <template #body>
          <view style="display:flex; align-items:center; padding:10px;">
            <!-- 左边图片 -->
            <image :src="item.dishImg ? `http://localhost:8090/carousel/getImg?fileName=${item.dishImg}` : '/static/default.png'" style="width:80px; height:80px; border-radius:8px" />

            <!-- 右边文字区域 -->
            <view
              style="flex:1; padding-left:20px; display:flex; flex-direction: column; justify-content: space-between; height:80px;"
            >
              <view style="font-size:18px; font-weight:bold;">{{ item.dishName }}</view>
              <view style="font-size:14px;">{{ item.specText }}</view>
              <view style="display:flex; justify-content: space-between; align-items: center;">
                <text style="font-size:14px;">￥{{ item.price.toFixed(2) }}/份</text>
                <view style="display:flex; align-items:center;">
                  <u-icon name="minus-circle" size="22" @click="decreaseQuantity(index)" />
                  <text style="margin: 0 10px;">{{ item.quantity }}</text>
                  <u-icon name="plus-circle" size="22" @click="increaseQuantity(index)" />
                </view>
              </view>
            </view>
          </view>
        </template>
      </u-card>
    </view>

    <!-- 总计 -->
    <u-divider>总计</u-divider>
	<!-- 页面底部操作栏 -->
	<view style="position: fixed; bottom: 0; left: 0; right: 0; height: 100rpx; background: #fff; display: flex; justify-content: space-between; align-items: center; padding: 0 30rpx; box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1); z-index: 999;">
	  <text class="u-type-primary" style="font-size: 18px;">合计金额：￥{{ totalMoney }}</text>
	  <view>
		<u-button type="success" size="mini" style="width: 50rpx; height: 70rpx; font-size: 26rpx;" @click="submitOrder">
		  提交订单
		</u-button>
	  </view>
	</view>

	
  </view>
</template>


<script setup>
import { ref, onMounted,computed } from 'vue'
import { submitOrders,payOrder } from '@/api/orderFoods.js'

const cartList = ref([])
//回去session的菜品信息
function getCarList(){
	const stored = uni.getStorageSync('cartList')
	console.log('确认订单页面 - 读取到的原始购物车数据:', stored)
	
	if (stored) {
	  cartList.value = stored
	  console.log('确认订单页面 - 设置后的cartList.value:', cartList.value)
	  console.log('确认订单页面 - 购物车中各商品的userId:', cartList.value.map(item => ({ dishName: item.dishName, userId: item.userId })))
	}
}
onMounted(() => {
  getCarList();
})

//计算订单金额
const totalMoney = computed(() => {
  return cartList.value.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2)
})

// 减数量
const decreaseQuantity = (index) => {
  const item = cartList.value[index]
  if (item.quantity > 1) {
    item.quantity--
  }
}

// 加数量
const increaseQuantity = (index) => {
  cartList.value[index].quantity++
}

//提交订单
function submitOrder(){
	console.log(cartList.value,"-----------87")
	
	// 获取当前登录用户的ID，确保使用的是最新的用户ID
	const currentUserId = uni.getStorageSync('userId')
	console.log('确认订单页面 - 当前缓存的userId:', currentUserId)
	console.log('确认订单页面 - 当前缓存userId类型:', typeof currentUserId)
	
	if (!currentUserId) {
		uni.showModal({
			title: '登录提示',
			content: '请先完成登录再提交订单',
			showCancel: false,
			confirmText: '去登录',
			success: () => {
				uni.switchTab({ url: '/pages/index/index' });
			}
		});
		return;
	}
	
	console.log('确认订单页面 - 提交订单使用的用户ID:', currentUserId)
	console.log('确认订单页面 - 购物车中第一个商品的用户ID:', cartList.value[0]?.userId)
	console.log('确认订单页面 - 购物车中所有商品的userId:', cartList.value.map(item => ({ dishName: item.dishName, userId: item.userId })))
	
	const orderData = {
	    cartList: cartList.value.map(item => ({
	      dishId: item.dishId,
	      dishName: item.dishName,
	      specs: item.specs,      // 是个数组，里面有每个规格
	      specText: item.specText,
	      quantity: item.quantity || 1, // 如果你有数量
	      price: item.price        // 每个菜的单价（如果有）
	    })),
	    totalMoney: totalMoney.value,
		tableNumber:cartList.value[0].tableNumber,
		storeId:cartList.value[0].storeId, //门店id
		userId: currentUserId //使用当前登录用户的ID，不依赖购物车中的ID
	  };
	  
	console.log('确认订单页面 - 最终提交的orderData:', orderData)
	console.log('确认订单页面 - 最终orderData中的userId:', orderData.userId)
	console.log('确认订单页面 - 最终orderData中userId类型:', typeof orderData.userId)
	
	submitOrders(orderData).then(res => {
		// 提交成功后清除本地缓存
		uni.removeStorageSync('cartList');
		// 同时清除页面响应式变量（如果需要）
		cartList.value = [];
		totalMoney.value = 0;
		console.log(res.tradNo,"---------109")
		// 弹出余额支付确认框
		    uni.showModal({
		      title: '确认支付',
		      content: '是否使用余额支付？',
		      confirmText: '余额支付',
		      cancelText: '取消',
		      success: function (modalRes) {
		        if (modalRes.confirm) {
		          // 用户点击了“余额支付”
		         usePay(res.tradNo);
		        } else if (modalRes.cancel) {
		          // 用户点击了“取消”按钮
		          uni.switchTab({
		            url: '/pages/userCenter/userCenter'
		          });
		        }
		      }
		    });
		
		
	})
	.catch(() => {
		uni.showToast({
		  type: 'error',
		  message: '操作失败，请检查网络',
		  duration: 2000
		})
	})
	
}
//支付
function usePay(orderNo){
	if(!orderNo){
		uni.showToast({ title: '订单错误',duration:2000});
	}
	payOrder(orderNo).then(res => {
		uni.showToast({
		    title: res.message || '支付成功',
		    icon: 'success',
		    duration: 3000
		  });
			uni.switchTab({
			  url: '/pages/userCenter/userCenter'
			});
	})
	.catch(err=> {
		uni.showToast({
		    title: err.message || '支付失败',
		    icon: 'none',
		    duration: 3000
		  });
		  setTimeout(() => {
		      uni.switchTab({
		        url: '/pages/userCenter/userCenter'
		      });
		    }, 1500);
	})
}
</script>

<style>
.order-page {
  background-color: #f8f8f8;
  min-height: 100vh;
}
</style>
